import React, { useEffect, useState, useMemo } from 'react';
import styled from 'styled-components';
import { commonService } from '@/flowService';

export const DataTypeMap = {
  String: '字符串',
  Integer: '整数',
  Double: '小数',
  Boolean: '布尔',
  Date: '日期',
  Time: '时间',
  Object: '对象',
  List: '集合',
};

const DataTypeName = styled.div`
  width: 110px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
`;

const DataTypeDisplay = ({ dataType }) => {
  const [objectDataTypeMap, setObjectDataTypeMap] = useState({});

  useEffect(() => {
    loadDataTypeList();
  }, []);

  const getDataTypeDisplayName = (dataType) => {
    if (!dataType) {
      return;
    }

    let displayName;
    if (dataType.type === 'Object') {
      displayName = objectDataTypeMap[dataType.objectKey];
    } else if (dataType.type === 'List') {
      const start = '列表<';
      let itemDisplayName;
      if (dataType.itemType) {
        itemDisplayName = getDataTypeDisplayName({
          type: dataType.itemType,
          objectKey: dataType.objectKey,
          objectStructure: dataType.objectStructure
        });
      }
      displayName = start + itemDisplayName + '>';
    } else {
      displayName = DataTypeMap[dataType.type];
    }
    return displayName;
  };

  const displayName = useMemo(() => {
    return getDataTypeDisplayName(dataType);
  }, [dataType, objectDataTypeMap]);

  const loadDataTypeList = async () => {
    const res = await commonService.dataType.getList();
    const dataTypeList = res || [];
    const newObjectDataTypeMap = dataTypeList
      .filter(item => item.dataTypeClassify === 3)
      .reduce((acc, item) => {
        if (item.objectKey) {
          acc[item.objectKey] = item.displayName;
        }
        return acc;
      }, {});
    setObjectDataTypeMap(newObjectDataTypeMap);
  };

  return <DataTypeName title={displayName}>{displayName}</DataTypeName>;
};

export default DataTypeDisplay; 